package com.vgemv.jsutilitysdk.JsView;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

import com.vgemv.jsutilitysdk.JsThread.JsThreadManager;


/**
 * 可以设置边框和圆角的View.
 */
public class JsView extends View {
    public Integer tag;
    public JsViewVm mVm;
    public int setupCount;

    public JsView(Context context) {
        super(context);
        mVm = new JsViewVm();
    }

    public void setupUiIfNeeded() {
        setupCount++;
        if(setupCount == 1) {
            JsThreadManager.runInMainThreadAtNextRunloop(new Runnable() {
                @Override
                public void run() {
                    setupUi();
                    setupCount = 0;
                }
            });
        }
    }

    private void setupUi() {
        if(mVm.isNeedDraw()) {
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        boolean isNeedDraw = mVm.isNeedDraw();
        //默认把绘制的数据全部放在内部.
        if(isNeedDraw) {
            Paint paint = new Paint();


            int width = this.getWidth();
            int height = this.getHeight();

            float padding = 0;
            if(mVm.mI_borderWidth != null) {
                padding = mVm.mI_borderWidth / 2.0f;
            }
            RectF rec = new RectF(padding, padding, width-padding, height-padding);
            float cornerRadius = mVm.mI_cornerRadius!=null?mVm.mI_cornerRadius:0;

            //绘制背景色
            if(mVm.mI_backgroundColor != null) {
                    paint.setColor(mVm.mI_backgroundColor);
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawRoundRect(rec, cornerRadius, cornerRadius, paint);

            }

            //绘制边框
            if(mVm.mI_borderWidth != null && mVm.mI_borderWidth > 0 && mVm.mI_borderColor != null) {
                paint.setColor(mVm.mI_borderColor);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(mVm.mI_borderWidth);
                canvas.drawRoundRect(rec, cornerRadius, cornerRadius, paint);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}
